from logging.handlers import TimedRotatingFileHandler
from airtest.core.api import *

import logging

import yaml


class BasePage():
    def __init__(self, poco=None):
        if poco is None:
            self.data = self.get_yaml_info('devices')[1]
            auto_setup(__file__, devices=[self.data])
            # 导入poco库
            from poco.drivers.android.uiautomation import AndroidUiautomationPoco
            # 实例化poco
            self.poco = AndroidUiautomationPoco(use_airtest_input=True, screenshot_each_action=False)
        else:
            self.poco = poco

    def start_app(self):
        #启动微信app
        return start_app("com.tencent.mm")

    def  seart_browser_app(self):

        '''启动浏览器'''
        return start_app("com.android.chrome")

    def close_app(self):
        return stop_app("com.tencent.mm")


    def close_browser_app(self):
        return stop_app("com.android.chrome")

    def get_yaml_info(self, name):
        '''
        获取yaml数据
        '''
        with open('../data/devices.yaml', 'r', encoding='utf-8') as f:
            self.data = yaml.safe_load(f)
            return self.data[f'{name}']

    # 设置 loging
    # fileHandler = logging.FileHandler(filename="../data/WeChat.log", encoding="utf-8")
    handler = TimedRotatingFileHandler(filename='../data/WeChat.log', encoding="utf-8", when='D', interval=1,
                                       backupCount=5)
    logging.getLogger().setLevel(logging.ERROR)
    logging.getLogger().setLevel(logging.INFO)
    formatter = logging.Formatter('%(asctime)s %(name)s %(levelname)s %(module)s:%(lineno)d %(message)s')
    handler.setFormatter(formatter)
    # fileHandler.setFormatter(formatter)
    logging.getLogger().addHandler(handler)

    # logging.handlers(handler)

    def log_info(self, msg):
        """
        添加日志
        :return: info级别日志
        """
        return logging.info(msg)

    def log_error(self, msg):
        """
              添加日志
              :return: error级别日志
              """
        return logging.error(msg)
